<?php
// 【最终完整版】m-merchant/register_handler.php

header('Content-Type: application/json; charset=utf-8');

include_once("../untils/conn.php");
mysqli_query($con, "set names utf8");

$response = ['code' => -99, 'msg' => '未知错误'];

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    $response = ['code' => -100, 'msg' => '无效的请求方式'];
    echo json_encode($response);
    exit;
}

$proxy_acc = $_POST['account'] ?? '';
$proxy_pass = $_POST['password'] ?? '';
$proxy_upid = $_POST['puid'] ?? '';
$proxy_name = $_POST['username'] ?? '';
$cr_time = time();

if (empty($proxy_acc) || empty($proxy_pass) || empty($proxy_upid) || empty($proxy_name)) {
    $response = ["code" => -1, "msg" => "所有项目均为必填项"];
    echo json_encode($response);
    exit;
}

if (!preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/', $proxy_pass)) {
    $response = ["code" => -2, "msg" => "密码过于简单，请设置不低于8位的字母和数字组合"];
    echo json_encode($response);
    exit;
}

$proxy_acc_safe = mysqli_real_escape_string($con, $proxy_acc);
$proxy_pass_safe = mysqli_real_escape_string($con, $proxy_pass);
$proxy_upid_safe = mysqli_real_escape_string($con, $proxy_upid);
$proxy_name_safe = mysqli_real_escape_string($con, $proxy_name);

$checkUsernameQuery = "SELECT * FROM proxy WHERE proxy_acc = '$proxy_acc_safe'";
$checkUsernameResult = mysqli_query($con, $checkUsernameQuery);

if (mysqli_num_rows($checkUsernameResult) > 0) {
    $response = ["code" => -1, "msg" => "该登录账号已存在"];
    echo json_encode($response);
    exit;
}

$checkInvitationCodeQuery = "SELECT group_id FROM proxy WHERE proxy_id = '$proxy_upid_safe'";
$checkInvitationCodeResult = mysqli_query($con, $checkInvitationCodeQuery);

if (mysqli_num_rows($checkInvitationCodeResult) == 0) {
    $response = ["code" => 3, "msg" => "邀请码不存在或无效"];
    echo json_encode($response);
    exit;
}

$parentProxyData = mysqli_fetch_assoc($checkInvitationCodeResult);
$new_group_id = $parentProxyData['group_id'];

$insertQuery = "INSERT INTO proxy (proxy_acc, proxy_pass, proxy_upid, cr_time, group_id, proxy_name) VALUES ('$proxy_acc_safe', '$proxy_pass_safe', '$proxy_upid_safe', '$cr_time', '$new_group_id', '$proxy_name_safe')";
$insertResult = mysqli_query($con, $insertQuery);

if ($insertResult) {
    $proxy_id = mysqli_insert_id($con);
    $sql_shopsy = "INSERT INTO shopsy (puid, shop_name) VALUES ('$proxy_id', '$proxy_name_safe')";
    $insertShopsyResult = mysqli_query($con, $sql_shopsy);

    if ($insertShopsyResult) {
        $response = ["code" => 2, "msg" => "注册成功！即将跳转到登录页面..."];
    } else {
        $response = ["code" => -3, "msg" => "系统错误(s)，请稍后再试！"];
    }
} else {
    $response = ["code" => -3, "msg" => "系统错误(p)，请稍后再试！"];
}
echo json_encode($response);
mysqli_close($con);
?>